﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using System.IO.IsolatedStorage;
using Newtonsoft.Json;

namespace MeetingFinder
{
    public partial class MainPage : PhoneApplicationPage
    {
        private string userID = null;


        public MainPage()
        {
            var currentApp = App.Current as App;
            
            //getting confirmed meeting items and adding to list
            WebClient getConfirmedMeetingProxy = new WebClient();
            getConfirmedMeetingProxy.DownloadStringCompleted += (senderC, eC) =>
            {
                if (eC.Error == null)
                {
                    string result = eC.Result;
                    var serverItemList = JsonConvert.DeserializeObject<List<ServerMeetingItem>>(result);

                    
                    currentApp._meetingItemList = new List<MeetingItem>();
                    foreach (ServerMeetingItem serverMeetingItem in serverItemList)
                    {
                        MeetingItem meeting = new MeetingItem();
                        meeting.convertToMeetingItem(serverMeetingItem, MeetingItem.Status.Confirmed);
                        currentApp._meetingItemList.Add(meeting);
                    }

                    //getting pending meeting items and adding to list
                    WebClient getPendingMeetingProxy = new WebClient();
                    getPendingMeetingProxy.DownloadStringCompleted += (senderP, eP) =>
                    {
                        if (eP.Error == null)
                        {
                            result = eP.Result;
                            serverItemList = JsonConvert.DeserializeObject<List<ServerMeetingItem>>(result);

                            foreach (ServerMeetingItem serverMeetingItem in serverItemList)
                            {
                                MeetingItem meeting = new MeetingItem();
                                meeting.convertToMeetingItem(serverMeetingItem, MeetingItem.Status.Pending);
                                currentApp._meetingItemList.Add(meeting);
                            }

                            //getting updated meeting items and adding to list
                            WebClient getUpdatedMeetingProxy = new WebClient();
                            getUpdatedMeetingProxy.DownloadStringCompleted += (senderU, eU) =>
                            {
                                if (eU.Error == null)
                                {

                                    result = eU.Result;
                                    serverItemList = JsonConvert.DeserializeObject<List<ServerMeetingItem>>(result);

                                    foreach (ServerMeetingItem serverMeetingItem in serverItemList)
                                    {
                                        MeetingItem meeting = new MeetingItem();
                                        meeting.convertToMeetingItem(serverMeetingItem, MeetingItem.Status.Updated);
                                        currentApp._meetingItemList.Add(meeting);
                                    }

                                    //getting notification items and adding to list
                                    WebClient getNotificationProxy = new WebClient();
                                    getNotificationProxy.DownloadStringCompleted += (senderN, eN) =>
                                    {
                                        if (eN.Error == null)
                                        {
                                            result = eN.Result;
                                            var serverNotificationItemList = JsonConvert.DeserializeObject<List<ServerNotificationItem>>(result);

                                            currentApp._notificationItemList = new List<MeetingItem>();
                                            foreach (ServerNotificationItem serverMeetingItem in serverNotificationItemList)
                                            {
                                                MeetingItem meeting = new MeetingItem();
                                                meeting.convertServerNotificationToMeetingItem(serverMeetingItem);
                                                currentApp._notificationItemList.Add(meeting);
                                            }

                                            //getting History items and add to list
                                            WebClient getHistoryProxy = new WebClient();
                                            getHistoryProxy.DownloadStringCompleted += (senderH, eH) =>
                                            {
                                                if (eH.Error == null)
                                                {
                                                    result = eH.Result;
                                                    serverItemList = JsonConvert.DeserializeObject<List<ServerMeetingItem>>(result);

                                                    currentApp._historyItemList = new List<MeetingItem>();
                                                    foreach (ServerMeetingItem serverMeetingItem in serverItemList)
                                                    {
                                                        MeetingItem meeting = new MeetingItem();
                                                        meeting.convertToMeetingItem(serverMeetingItem, MeetingItem.Status.History);
                                                        currentApp._historyItemList.Add(meeting);
                                                    }

                                                    //required lists have been pulled from server, now initialize elements on main page
                                                    InitializeComponent();

                                                    InitializeApplicationBar();

                                                    AddButtonToAppBar("/Assets/Images/add.png", "New Meeting", CreateMeetingButton_Click);

                                                    //AddButtonToAppBar("/Assets/Images/check.png", "Login To IVLE", LoginToIVLEButton_Click);

                                                    //SetUserID(null);

                                                    userID = GetUserID();
                                                    if (userID == "UserID.txt does not exist" || userID == "")
                                                        LandingPage.Title = "Please Login to IVLE";
                                                    else
                                                        LandingPage.Title = userID;

                                                    InitializeLocaLists();
                                                }
                                            };//end history list
                                            getHistoryProxy.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._getHistoryAPI + currentApp._userID, UriKind.Absolute));
                                        }
                                    };//end notification list

                                    getNotificationProxy.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._getNotificationAPI + currentApp._userID, UriKind.Absolute));
                                }
                            };//end updated list

                            getUpdatedMeetingProxy.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._getUpdatedAPI + currentApp._userID, UriKind.Absolute));
                        }
                    };//end pending list


                    getPendingMeetingProxy.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._getPendingAPI + currentApp._userID, UriKind.Absolute));

                }
            };//end confirmed list
            getConfirmedMeetingProxy.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._getConfirmedAPI + currentApp._userID, UriKind.Absolute));

        }


//Private / Helper Methods----------------------------------------------------------------------------------

        //creates new instance of Application bar
        private void InitializeApplicationBar()
        {
            ApplicationBar = new ApplicationBar();

            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 1.0;
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = true;
        }

        //crates a new button on application bar
        //sets icon image
        //set click even handler
        private void AddButtonToAppBar(String IconPath, String DescriptionText, EventHandler ClickEventHandler)
        {
            ApplicationBarIconButton CreateNewMeetingButton = new ApplicationBarIconButton();
            CreateNewMeetingButton.IconUri = new Uri(IconPath, UriKind.Relative);
            CreateNewMeetingButton.Text = DescriptionText;
            ApplicationBar.Buttons.Add(CreateNewMeetingButton);
            CreateNewMeetingButton.Click += new EventHandler(ClickEventHandler);
        }

        //test function to set userID
        private void SetUserID(string userID)
        {
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

            //create new file
            using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("UserID.txt", FileMode.Create, FileAccess.Write, myIsolatedStorage)))
            {
                string someTextData = userID;
                writeFile.WriteLine(someTextData);
                writeFile.Close();
            }
        }

        //reads userID from text file in isolated storage
        private string GetUserID()
        {
            string userID;
            try
            {
                IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("UserID.txt", FileMode.Open, FileAccess.Read);

                using (StreamReader reader = new StreamReader(fileStream))
                {    //Visualize the text data in a TextBlock text
                    userID = reader.ReadLine();
                }
            }
            catch (IsolatedStorageException ex)
            {
                userID = "UserID.txt does not exist";
            }
            return userID;
        }

        //Sends initializes local Lists 
        private void InitializeLocaLists()
        {
            //initializing meeting list for Main Page Pivot
            var received = App.Current as App;

            var meetingByStatus = from meeting in received._meetingItemList
                                    group meeting by meeting._meetingStatus into m
                                    orderby m.Key
                                    select new Group<MeetingItem>(m.Key.ToString(), m);
            this.meetingList.ItemsSource = meetingByStatus; 

            //initialize project group list
            received._projectGroupList = CreateProjectGroupTestList();

            //initialize History List
            var historyByGroup = from historyItem in received._historyItemList
                                 group historyItem by historyItem._groupID into h
                                  orderby h.Key
                                  select new Group<MeetingItem>(h.Key, h);
            this.historyList.ItemsSource = historyByGroup; 

            //initizlize Notification list
            var notificationByDate = from notificationItem in received._notificationItemList
                                     group notificationItem by notificationItem._meetingDateTime.Date into n
                                 orderby n.Key
                                 select new Group<MeetingItem>(n.Key.ToShortDateString(), n);
            this.notificationList.ItemsSource = notificationByDate; 

        }
        
        //just creates a list for testing, get actual list from a main store, may be dict
        private List<ProjectGroup> CreateProjectGroupTestList()
        {
            List<ProjectGroup> testList = new List<ProjectGroup>();

            for (int i = 0; i < 5; i++)
            {
                ProjectGroup group = new ProjectGroup();
                group._groupName = "Group " + i;
                group._moduleName = "Module " + i + i;

                testList.Add(group);
            }
            return testList;
        }


//event handlers---------------------------------------------------------------------------------------------

        public void MeetingItem_Click(object sender, RoutedEventArgs e)
        {
            var toSend = App.Current as App;
            TextBlock senderobj = (TextBlock) e.OriginalSource;
            toSend._meetingSelected = senderobj.Text; ;
            NavigationService.Navigate(new Uri("/EditMeetingForm.xaml", UriKind.Relative));
        }

        private void LoginToIVLEButton_Click(object sender, EventArgs e)
        {
            // navigate
            this.NavigationService.Navigate(new Uri("/IVLElogin.xaml", UriKind.Relative));
        }

        private void LandingPage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (((Pivot)sender).SelectedIndex)
            {
                case 0:
                    ApplicationBar.IsVisible = true;
                    break;

                case 1:
                    ApplicationBar.IsVisible = false;
                    break;

                case 2:
                    ApplicationBar.IsVisible = false;
                    break;
            }
        }

        private void CreateMeetingButton_Click(object sender, EventArgs e)
        {
            if (userID == "UserID.txt does not exist" || userID == "")
                this.NavigationService.Navigate(new Uri("/IVLElogin.xaml", UriKind.Relative));
            else
                this.NavigationService.Navigate(new Uri("/GroupSelection.xaml", UriKind.Relative));
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            userID = GetUserID();
            if (userID == "UserID.txt does not exist" || userID == "")
                this.NavigationService.Navigate(new Uri("/IVLElogin.xaml", UriKind.Relative));
            else
                LandingPage.Title = userID;
        }

    }
}